//
//  ADAlertViewController.swift
//  ADKit
//
//  Created by Adoma on 2022/11/26.
//

import UIKit
import RxCocoa
import NSObject_Rx

public class ADAlertViewController: UIViewController {
    
    public class Config {
        
        var title: String?
        var message: String?
                
        var contentColor = UIColor.init(hex: "#373248")
        var contentCornerRadius: CGFloat = 12

        var titleFont = UIFont.pingfang(with: 16, style: .medium)
        var titleColor = UIColor.white

        var messageFont = UIFont.pingfang(with: 14, style: .regular)
        var messageColor = UIColor.white.alpha(0.8)
        
        var itemRadius = AD_ZOOM_WIDTH(8)
        var itemHeight = AD_ZOOM_WIDTH(40)
    
        var touchOutsideDismiss = false
    }

    public convenience init(title: String? = nil, message: String? = nil) {
        let config = Config()
        config.title = title
        config.message = message
        self.init(config: config)
    }
    
    public init(config: Config) {
        self.config = config
        super.init(nibName: nil, bundle: nil)
        modalTransitionStyle = .crossDissolve
        modalPresentationStyle = .overFullScreen
    }
    
    let config: Config
    private var actions: [ADAlertActionItem] = []
    
    public override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .black.alpha(0.6)
        
        let content = UIControl()
        content.backgroundColor = config.contentColor
        content.layer.cornerRadius = config.contentCornerRadius
        view.addSubview(content)
        content.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(AD_ZOOM_WIDTH(47))
            make.centerY.equalToSuperview()
            make.height.greaterThanOrEqualTo(AD_ZOOM_WIDTH(150))
        }
        
        let title = UILabel()
        title.numberOfLines = 0
        title.textAlignment = .center
        title.text = config.title
        title.font = config.titleFont
        title.textColor = config.titleColor
        content.addSubview(title)
        title.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(AD_ZOOM_WIDTH(20))
            make.top.equalToSuperview().inset(AD_ZOOM_WIDTH(25))
        }
        
        let message = UILabel()
        message.numberOfLines = 0
        message.textAlignment = .center
        message.text = config.message
        message.font = config.messageFont
        message.textColor = config.messageColor
        content.addSubview(message)
        message.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(AD_ZOOM_WIDTH(20))
            make.top.equalTo(title.snp.bottom).offset(AD_ZOOM_WIDTH(18))
            make.bottom.lessThanOrEqualToSuperview().inset(AD_ZOOM_WIDTH(94))
        }
        
        let items = actions.enumerated().map { configAction(item: $0.element, index: $0.offset) }
        let actionContent = UIStackView(arrangedSubviews: items)
        actionContent.axis = .horizontal
        actionContent.distribution = .fillEqually
        actionContent.alignment = .fill
        actionContent.spacing = AD_ZOOM_WIDTH(16)
        content.addSubview(actionContent)
        actionContent.snp.makeConstraints { make in
            make.bottom.equalToSuperview().inset(AD_ZOOM_WIDTH(26))
            make.left.right.equalToSuperview().inset(AD_ZOOM_WIDTH(16))
            make.height.equalTo(config.itemHeight)
        }
    }
    
    func configAction(item: ADAlertActionItem, index: Int) -> UIButton {
        let action = UIButton(type: .custom)
        action.tag = index
        action.setTitle(item.text, for: .normal)
        action.setTitleColor(item.textColor, for: .normal)
        action.titleLabel?.font = item.font
        if let image = item.image {
            action.setBackgroundImage(image, for: .normal)
        } else {
            action.backgroundColor = item.backgroundColor
            action.layer.cornerRadius = config.itemRadius
            action.layer.masksToBounds = true
        }
        action.rx.tap.subscribe(onNext: {[weak self] _ in
            if let callback = item.callback {
                callback()
            }
            else if let callback = item.callback2 {
                callback(action.tag)
            }
            self?.dismiss(animated: true)
        }).disposed(by: rx.disposeBag)
        return action
    }
    
    // MARK: - 默认左取消右确认
    public func twoAction(actoins: (ADAlertActionItem, ADAlertActionItem)? = nil, callback: ((Int)->Void)?) {
        if let actoins = actoins {
            if actoins.0.callback == nil {
                actoins.0.callback2 = callback
            }
            if actoins.1.callback == nil {
                actoins.1.callback2 = callback
            }
            
            actions.append(contentsOf: [actoins.0, actoins.1])
        } else {
            let cancel = ADAlertActionItem(title: "取消", style: .cancel)
            cancel.callback2 = callback
            
            let confirm = ADAlertActionItem(title: "确定", style: .confim)
            confirm.callback2 = callback
            
            actions.append(contentsOf: [cancel, confirm])
        }
    }
    
    // MARK: - 默认确认
    public func addAction(action: ADAlertActionItem? = nil, callback: (()->Void)? = nil) {
        if let action = action {
            if action.callback == nil {
                action.callback = callback
            }
            actions.append(action)
        } else {
            let confirm = ADAlertActionItem(title: "确定", style: .confim, callback: callback)
            actions.append(confirm)
        }
    }
    
    public func show() {
        WindowManager.currentViewController?.present(self, animated: true)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if config.touchOutsideDismiss == false {
            return
        }
        dismiss(animated: true)
    }
}
 
public class ADAlertActionItem {
    
    enum Style {
        case `default`, cancel, confim
    }
    
    let backgroundColor: UIColor
    let text: String
    let font: UIFont
    let textColor: UIColor
    let image: UIImage?
    
    fileprivate var callback: (()->Void)?
    fileprivate var callback2: ((Int)->Void)?
    
    convenience init(title: String, style: Style = .default, callback: (()->Void)? = nil) {
        var textColor = UIColor.black
        var backgroundColor: UIColor
        var font: UIFont = ._regular(15)
        switch style {
        case .confim:
            font = ._medium(15)
            textColor = .white
            backgroundColor = ADKit.Color.k0170C9
        case .cancel:
            textColor = .init(hex: "#DBDBDB")
            backgroundColor = .init(hex: "#A8A8A8", alpha: 0.5)
        default:
            textColor = .black
            backgroundColor = .white
        }
        self.init(text: title, font: font, textColor: textColor, background: backgroundColor, callback: callback)
    }
    
    public init(text: String, font: UIFont, textColor: UIColor, background: UIColor, image: UIImage? = nil , callback: (()->Void)? = nil) {
        self.callback = callback
        self.backgroundColor = background
        self.image = image
        self.text = text
        self.font = font
        self.textColor = textColor
    }
}
